﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;

namespace Cemetary_DataBase
{
    public struct Entry
    {
        public string s_PurchaceLastName;
        public string s_PurchaceFirstName;
        public string s_PurchaceCity;
        public string s_PurchaceState;
        public string s_PurchaceDate;
        public string s_PurchacePrice;
        public string s_PurchacePlots;
        public string s_Section;
        public string s_Cemetery;
        public string s_Index;
        public string s_ReceptID;
        public string s_BuryCremEmpty;
        public string s_BuryedLocation;
        public string s_BuryedFirstName;
        public string s_BuryedLastName;
        public string s_BuryedMidMaidName;
        public string s_BuryedBirthDate;
        public string s_BuryedDeathDate;
        public string s_Notes;
        public string s_Source;
        public int i_BoxX;
        public int i_BoxY;
        public int i_BoxW;
        public int i_BoxH;
        public int i_BoxID;
    }
    //container for the sub parts of the cemtary such as Alpha 2E, 
    //it has the nice name of the section, the full folder path, and a entry array of all the json files in it
    public struct SubSection
    {
        public string s_Name;
        public string s_FullPath;
        public List<Entry> el_Entrys;
        public SubSection(string Name, string Path)
        {
            s_Name = Name;
            s_FullPath = Path;
            el_Entrys = new List<Entry>();
        }

    }

    public partial class Form1 : Form
    {
        public List<Entry> LoadedEntrys = new List<Entry>();
        public List<string> ValidFolders = new List<string>();
        public string Dir;
        public List<SubSection> TempSubSections = new List<SubSection>();
        public List<SubSection> AllSubSections = new List<SubSection>();
        public TreeNode[] CemeteryNodes = new TreeNode[] { };
        public Entry ActiveEntry = new Entry();
        public bool isLoadingEntry;
        public bool hasEntryLoaded;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ReloadDataBaseFromDisk();
        }
        void ReloadDataBaseFromDisk()
        {
            isLoadingEntry = false;
            hasEntryLoaded = false;
            treeView1.Nodes.Clear();
            LoadedEntrys.Clear();
            ValidFolders.Clear();
            TempSubSections.Clear();
            
            LoadTopDirs();
            for (int Index = 0; Index < ValidFolders.Count(); Index++)
            {
                LoadSubSectionDirs( ValidFolders[Index] );
                TreeNode[] Temp2 = new TreeNode[TempSubSections.Count()];
                for (int Index1 = 0; Index1 < TempSubSections.Count(); Index1++)
                {
                    //get the files into the temp subsection
                    LoadSubSectionValidFiles(TempSubSections[Index1]);
                    //add the subsection to the list of all of them for editing
                    AllSubSections.Add(TempSubSections[Index1]);
                    //make treenodes matching the subsections and make an array of them
                    TreeNode[] Temp = SubSectionToTreeNodes(TempSubSections[Index1]);
                    TreeNode SubSection = new TreeNode(TempSubSections[Index1].s_Name, Temp);
                    Temp2[Index1] = SubSection;
                    
                }
                CemeteryNodes[Index] = AppendTreeNodes(CemeteryNodes[Index], Temp2);
                TempSubSections.Clear();
            }
            LoadTreeview(CemeteryNodes);
            treeView1.ExpandAll();
        }
        void LoadTreeview(TreeNode[] Input)
        {
            treeView1.Nodes.Clear();
            for (int Index = 0; Index < Input.Count(); Index++)
            {
                treeView1.Nodes.Add(Input[Index]);
            }
        }

        void LoadTopDirs()
        {
            Dir = Directory.GetCurrentDirectory();
            string[] CurDir = Directory.GetDirectories(Dir);
            toolStripStatusLabel1.Text = "Current Working Directory: "+Dir;
            for (int Index = 0; Index < CurDir.Length; Index++)
            {
                string DirName = CurDir[Index].Substring(Dir.Length + 1);
                string SubPrefix = DirName.Substring(0, 3).ToLower();
                if (SubPrefix == "sub")
                {
                    ValidFolders.Add(CurDir[Index]);
                }
            }
            //make all the top level treenodes
            CemeteryNodes = new TreeNode[ValidFolders.Count];
            for(int Index = 0; Index < ValidFolders.Count; Index++)
            {
                CemeteryNodes[Index] = new TreeNode( ValidFolders[Index].Substring(Dir.Length + 5) );
            }
        }
        void LoadSubSectionDirs(string SubDir)
        {
            string[] CemeteryDir = Directory.GetDirectories(SubDir);
            if (CemeteryDir.Length > 0)
            {
                for (int Index = 0; Index < CemeteryDir.Length; Index++)
                {
                    SubSection New = new SubSection(CemeteryDir[Index].Substring(SubDir.Length + 1), CemeteryDir[Index]);
                    TempSubSections.Add(New);
                }
            }
        }
        void LoadSubSectionValidFiles(SubSection SubSection)
        {
            //get all the text files for json parsing
            string[] AllFiles = Directory.GetFiles(SubSection.s_FullPath);
            if (AllFiles.Length > 0)
            {
                for (int Index = 0; Index < AllFiles.Length; Index++)
                {
                    string Ext = AllFiles[Index].Substring(AllFiles[Index].Length - 4);
                    if (Ext == ".txt")
                    {
                        string JsonText = File.ReadAllText(AllFiles[Index]);
                        Entry Temp = new Entry();
                        Temp = JsonConvert.DeserializeObject<Entry>(JsonText);
                        SubSection.el_Entrys.Add(Temp);
                        LoadedEntrys.Add(Temp);
                    }
                }
            }
        }
        TreeNode[] SubSectionToTreeNodes(SubSection SubSection)
        {
            TreeNode[] TreeNodes = new TreeNode[SubSection.el_Entrys.Count()];
            for(int Index = 0; Index < TreeNodes.Length; Index++)
            {
                TreeNodes[Index] = new TreeNode("" + SubSection.el_Entrys[Index].s_Index);
            }
            return TreeNodes;
        }
        TreeNode AppendTreeNodes(TreeNode Parrent, TreeNode[] Children)
        {
            TreeNode Temp = new TreeNode(Parrent.Text, Children);
            return Temp;
        }


        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                for (int Index = 0; Index < AllSubSections.Count; Index++)
                {
                    if (AllSubSections[Index].s_Name == treeView1.SelectedNode.Parent.Text)
                    {
                        for (int Index1 = 0; Index1 < AllSubSections[Index].el_Entrys.Count; Index1++)
                        {
                            if (AllSubSections[Index].el_Entrys[Index1].s_Index == treeView1.SelectedNode.Text)
                            {
                                ActiveEntry = AllSubSections[Index].el_Entrys[Index1];
                                loadActiveEntry();
                                hasEntryLoaded = true;
                            }
                        }
                    }
                }
            }
            catch
            {

            }
            
            
        }
        private void ReloadToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ReloadDataBaseFromDisk();
        }

        private void CemeteryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string NewDir = Prompt.ShowDialog("Enter New Cemetery Name Below", "New Cemetery Prompt");
            if(NewDir != "")
            {
                Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Sub_" + NewDir);
                ReloadDataBaseFromDisk();
            }
        }

        private void SubSectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            if (hasValidRootSelected())
            {
                string NewDir = Prompt.ShowDialog("Enter New SubSection Name Below.", "New SubSection Prompt");
                if (NewDir != "")
                {
                    Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Sub_" + treeView1.SelectedNode.Text + "\\" + NewDir);
                    ReloadDataBaseFromDisk();
                }
            }
            else
            {
                MessageBox.Show("You need to have a cemetery selected.");
            }
            
        }
        bool hasValidRootSelected()
        {
            string RDir = Directory.GetCurrentDirectory();
            string[] RDirs = Directory.GetDirectories(RDir);
            bool valid = false;
            for(int Index = 0; Index < RDirs.Length; Index++)
            {
                if (RDir + "\\Sub_" + treeView1.SelectedNode.Text == RDirs[Index])
                {
                    valid = true;
                }
            }
            return valid;
        }
        bool hasValidSubSectionSelected()
        {
            bool valid = false;
            try
            {
                string SDir = Directory.GetCurrentDirectory() + "\\Sub_" + treeView1.SelectedNode.Parent.Text;
                string[] SDirs = Directory.GetDirectories(SDir);
                for (int Index = 0; Index < SDirs.Length; Index++)
                {
                    if (SDir + "\\" + treeView1.SelectedNode.Text == SDirs[Index])
                    {
                        valid = true;
                    }
                }
            }
            catch
            {

            }
            return valid;
        }

        private void entryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (hasValidSubSectionSelected())
            {
                string NewEntryName = Prompt.ShowDialog("Enter New Entry Name Below.", "New Entry Prompt");
                if (NewEntryName != "")
                {
                    Entry NewEntry = new Entry();
                    NewEntry.s_Index = NewEntryName;
                    string JsonText = JsonConvert.SerializeObject(NewEntry);
                    File.WriteAllText(Directory.GetCurrentDirectory() + "\\Sub_" + treeView1.SelectedNode.Parent.Text + "\\" + treeView1.SelectedNode.Text + "\\" + NewEntryName + ".txt", JsonText);
                    ReloadDataBaseFromDisk();
                }
            }
            else
            {
                MessageBox.Show("You need to have a Subsection selected.");
            }
        }

        int searchEntrysLastName(string Search)
        {
            int Output = -1;
            for(int Index = 0; Index < LoadedEntrys.Count(); Index++)
            {

                if (LoadedEntrys[Index].s_PurchaceLastName.ToLower() == Search)
                {
                    Output = Index;
                    break;
                }



            }
            return Output;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //delete a entry
            try
            {
                string Try = treeView1.SelectedNode.Parent.Parent.Text;
                File.Delete(Directory.GetCurrentDirectory() + "\\Sub_" + Try + "\\" + treeView1.SelectedNode.Parent.Text + "\\" + treeView1.SelectedNode.Text + ".txt");
                ReloadDataBaseFromDisk();
            }
            catch
            {
                MessageBox.Show("A Entry was not Selected");
            }
        }
        //loads the active entry struct into the textboxes for editing
        public void loadActiveEntry()
        {
            isLoadingEntry = true;
            purchasefirst.Text = ActiveEntry.s_PurchaceFirstName;
            purchaselast.Text = ActiveEntry.s_PurchaceLastName;
            receptid.Text = ActiveEntry.s_ReceptID;
            purchasecity.Text = ActiveEntry.s_PurchaceCity;
            purchasestate.Text = ActiveEntry.s_PurchaceState;
            purchaseprice.Text = ActiveEntry.s_PurchacePrice;
            purchaseplots.Text = ActiveEntry.s_PurchacePlots;
            buriedcemetery.Text = ActiveEntry.s_Cemetery;
            buriedsection.Text = ActiveEntry.s_Section;
            buriedlocation.Text = ActiveEntry.s_BuryedLocation;
            buriedorcremated.Text = ActiveEntry.s_BuryCremEmpty;
            buriedfirst.Text = ActiveEntry.s_BuryedFirstName;
            buriedmiddle.Text = ActiveEntry.s_BuryedMidMaidName;
            buriedlast.Text = ActiveEntry.s_BuryedLastName;
            buriednotessource.Text = ActiveEntry.s_Source;
            buriednotes.Text = ActiveEntry.s_Notes;
            purchasedate.Text = ActiveEntry.s_PurchaceDate;
            buriedbirthdate.Text = ActiveEntry.s_BuryedBirthDate;
            burieddeathdate.Text = ActiveEntry.s_BuryedDeathDate;
            isLoadingEntry = false;
            //MessageBox.Show("Loaded Entry");
        }
        public void SaveEntryToDisk()
        {
            string JsonText = JsonConvert.SerializeObject(ActiveEntry);
            MessageBox.Show("Saved");
            File.WriteAllText(Directory.GetCurrentDirectory() + "\\Sub_" + treeView1.SelectedNode.Parent.Parent.Text + "\\" + treeView1.SelectedNode.Parent.Text + "\\" + ActiveEntry.s_Index + ".txt", JsonText);
            ReloadDataBaseFromDisk();
        }
        //all the value changes back to the active entry and saved
        private void purchasefirst_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            {
                ActiveEntry.s_PurchaceFirstName = purchasefirst.Text;
                
            }
        }

        private void purchaselast_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_PurchaceLastName = purchaselast.Text;
                
            }
        }

        private void receptid_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_ReceptID = receptid.Text;
            }
        }

        private void purchasecity_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_PurchaceCity = purchasecity.Text;

            }
        }

        private void purchasestate_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_PurchaceState = purchasestate.Text;

            }
        }

        private void purchaseprice_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_PurchacePrice = purchaseprice.Text;

            }
        }

        private void purchaseplots_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_PurchacePlots = purchaseplots.Text;

            }
        }

        private void buriedcemetery_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_Cemetery = buriedcemetery.Text;

            }
        }

        private void buriedsection_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_Section = buriedsection.Text;

            }
        }

        private void buriedlocation_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_BuryedLocation = buriedlocation.Text;

            }
        }

        private void buriedorcremated_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_BuryCremEmpty = buriedorcremated.Text;

            }
        }

        private void buriedfirst_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_BuryedFirstName = buriedfirst.Text;

            }
        }

        private void buriedmiddle_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_BuryedMidMaidName = buriedmiddle.Text;

            }
        }

        private void buriedlast_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_BuryedLastName = buriedlast.Text;

            }
        }

        private void buriednotessource_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_Source = buriednotessource.Text;

            }
        }

        private void buriednotes_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_Notes = buriednotes.Text;

            }
        }

        private void purchasedate_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_PurchaceDate = purchasedate.Text;

            }
        }

        private void buriedbirthdate_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_BuryedBirthDate = buriedbirthdate.Text;

            }
        }

        private void burieddeathdate_TextChanged(object sender, EventArgs e)
        {
            if (!isLoadingEntry)
            { 
                ActiveEntry.s_BuryedDeathDate = burieddeathdate.Text;
            }
        }

        private void save_Click(object sender, EventArgs e)
        {
            if (hasEntryLoaded)
            {
                SaveEntryToDisk();
            }
        }

    }
    public static class Prompt
    {
        public static string ShowDialog(string text, string caption)
        {
            Form prompt = new Form();
            prompt.Width = 320;
            prompt.Height = 120;
            prompt.Text = caption;
            prompt.StartPosition = FormStartPosition.CenterScreen;
            prompt.MinimizeBox = false;
            prompt.MaximizeBox = false;
            prompt.MinimumSize = new Size(320, 120);
            prompt.MaximumSize = new Size(800, 120);

            Label textLabel = new Label() { Left = 8, Top = 8, Width = 288, Text = text };
            TextBox textBox = new TextBox() { Left = 8, Top = 24, Width = 288 };
            Button confirmation = new Button() { Text = "Ok", Left = 196, Width = 100, Top = 48 };

            textLabel.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            textBox.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
            confirmation.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;

            confirmation.Click += (sender, e) => { prompt.Close(); };
            prompt.Controls.Add(textBox);
            prompt.Controls.Add(confirmation);
            prompt.Controls.Add(textLabel);
            prompt.AcceptButton = confirmation;
            prompt.ShowDialog();
            return textBox.Text;
        }
    }
}
